package demo.projecttask.web;

import demo.base.JSONUtils;
import demo.common.id.IdService;
import demo.common.model.PageResult;
import demo.common.model.SqlCondition;
import demo.common.web.BaseController;
import demo.common.web.HttpUtils;
import demo.projecttask.dao.TaskDao;
import demo.projecttask.model.Task;
import demo.projecttask.model.TaskCondition;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;


/**
 * Created by llq on 2017/11/1.
 */
@RestController
@RequestMapping("/tasks")
public class TasksController extends BaseController<Task, TaskCondition> {

    private static final Logger logger = LoggerFactory.getLogger(TasksController.class);

    @Autowired
    private TaskDao taskDao;

    @Autowired
    private IdService idService;

    @Override
    protected Object handlePaging(Integer userId, TaskCondition condition) {
        PageResult pageResult = new PageResult();
        pageResult.setTotal(taskDao.pagingTotal(condition));
        pageResult.setData(taskDao.pagingData(condition));
        return pageResult;
    }

    @Override
    protected Object handleCreate(Integer userId, Task task) {
        task.setId(idService.nextId());
        taskDao.insert(task);

        if (!task.topTask()) {
            Task parentTask = taskDao.get(task.getParentid());
            parentTask.addChildCount(1);
            taskDao.updateByAnnotation(parentTask, Task.UpdateChildCount.class);
        }

        return task;
    }

    @Override
    protected Object handleGet(Integer userId, int id) {
        return taskDao.get(id);
    }

    @Override
    protected Object handlePut(Integer userId, int id, Task task) {
        task.setId(id);
        taskDao.updateByAnnotation(task, Task.Update.class);
        return taskDao.get(id);
    }

    @Override
    protected Object handleDelete(Integer userId, int id) {
        // 注意: 为了简单处理,这里没有添加事务处理
        Task task = taskDao.get(id);

        if (!task.topTask()) {
            Task parentTask = taskDao.get(task.getParentid());
            parentTask.subChildCount(1);
            taskDao.updateByAnnotation(parentTask, Task.UpdateChildCount.class);
        }

        deleteTaskAndChildren(task);

        return JSONUtils.EMPTY_OBJECT;
    }

    private void deleteTaskAndChildren(Task task) {

        List<Task> tasks = new ArrayList<>();
        tasks.add(task);
        int index = 0;
        Task current = null;
        while (index < tasks.size()) {
            current = tasks.get(index);
            tasks.addAll(taskDao.find(SqlCondition.create().eq("parentid", current.getId()).eq("deleted", false)));
            index++;
        }

        logger.info("删除" + task.getId() + "(" + task.getName() + ")节点及其子节点,总共" + tasks.size() + "个");
        for (Task task1 : tasks) {
            task1.delete();
            taskDao.updateByAnnotation(task1, Task.UpdateDeleteStatus.class);
        }

    }

    @GetMapping("/{id}/children")
    public Object children(@PathVariable int id, HttpServletRequest request, HttpServletResponse response) {
        try {
            return taskDao.find(SqlCondition.create().eq("parentid", id).eq("deleted", false));
        } catch (Exception ex) {
            return handleException(ex, request, response);
        }
    }

}
